#!/bin/sh
# Copyright (c) 2011, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.
# created on 2011-01-01

main(){
 [ $# -lt 1 ] && {
  echo "usage: $0 <PID>" >&2
  exit 1
 }
 local OPTS=""
 local ROOTS=""
 while [ $# -gt 0 ] && [ "$1" != "--" ] ;do
  case "$1" in
   -*) OPTS="$OPTS $1";;
   *)  ROOTS="$ROOTS $1"
  esac
  shift
 done
 if [ $# -gt 0 ] ;then
  shift
  OPTS="$OPTS $@"
 fi
 local PROTECT=$$
 for ROOT in $ROOTS ;do
  reckill $ROOT $PROTECT $OPTS
 done
}

reckill(){ [ $# -lt 2 ] && exit 1
 local ROOT=$1
 local PROTECT=$2
 shift 2
 local OPTS="$@"
 local PIDS="`gettreenodes $ROOT $PROTECT`"
 echo kill $OPTS $PIDS >&2
 kill $OPTS $PIDS
}

gettreenodes(){ #TODO: ps --no-heading -o pid --ppid "$@"
 [ $# -lt 2 ] && exit 1
 local NODE=$1
 local PRUNE=$2
 [ $NODE -eq $PRUNE ] && return
 echo $NODE
 getchildren $NODE |
 while read CHILD ;do
  gettreenodes $CHILD $PRUNE
 done
}

getchildren(){ [ $# -ne 1 ] && exit 1
 local NODE=$1
 ps -ef |
 awk '$3 == '${NODE}' { print $2 }'
}

main "$@"
